package cn.toolck.minitomcat.runner;

import cn.toolck.minitomcat.container.Context;
import cn.toolck.minitomcat.container.Wapper;
import cn.toolck.minitomcat.map.Mapper;
import cn.toolck.minitomcat.pojo.Request;
import cn.toolck.minitomcat.pojo.Response;
import cn.toolck.minitomcat.service.Service;
import cn.toolck.minitomcat.servlet.HttpServlet;
import cn.toolck.minitomcat.util.HttpProtocolUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * @ClassName WorkRunner
 * @Description TODO
 * @Author Toolck Rin
 * @Date 2021/3/17 23:05
 * @Version 1.0
 **/
public class Worker implements Runnable {
    private Socket socket;
    private Service service;

    public Worker(Socket socket, Service service) {
        this.socket = socket;
        this.service = service;
    }

    public Worker() {
    }

    @Override
    public void run() {
        InputStream in = null;
        try {
            in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            Request request = new Request(in);
            System.out.println(request.getUrl());
            Response response = new Response(out);
            String url = request.getUrl();
            String host = request.getHost();

            Mapper mapper = service.getEngine().getMapper();
            Mapper.MappedContext mappedContext = mapper.find(host, url);
            if (mappedContext == null) {
                out.write(HttpProtocolUtil.getHttpContext404().getBytes());
                out.flush();
                //关闭
                out.close();
                in.close();
                socket.close();
                return;
            }
            List<Mapper.MappedWapper> wappers = mappedContext.wappers;
            String suburl = url.substring(mappedContext.getName().length() + 1);
            int i = mapper.find(suburl, wappers);
            if (i < 0) {
                // 调用静态资源
                response.outputHtml(suburl, mappedContext);
            } else {
                Mapper.MappedWapper wapper = wappers.get(i);
                HttpServlet servlet = wapper.getObj().getServlet();
                servlet.service(request, response);
            }
            out.flush();
            //关闭
            out.close();
            in.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
